package org.noote.test_camera_bc_server;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.noote.libs.camera.CameraInterface;
import org.noote.libs.camera.broadcast.CameraBroadcast;
import org.noote.libs.camera.helper.Helper_Camera;
import org.noote.libs.camera.preview.CameraPreview;
import org.noote.libs.tcpip.helper.Helper_WiFi;

public class TestCameraServer_Activity extends Activity {
	private static final String LOG_TAG = "TestCameraServer_Activity";
	
	private CameraInterface mCamera = new CameraInterface();
	private CameraPreview mPreview = null;
	private CameraBroadcast mBroadcast = null;
	private String m_sCurrentIPAddress = "0.0.0.0";
	private int m_iServerPort = 8088;

	protected static final int MESSAGE_UI_LOG=0;
	protected static final int MESSAGE_UI_TOAST=1;

	final Handler _UI_Handler = new Handler() {
	    @Override
		public void handleMessage(Message msg) {
	        switch (msg.what) {

	        case MESSAGE_UI_LOG:
	        {
	    		TextView textViewLog = (TextView) findViewById(R.id.textViewLog);

	    		textViewLog.setText(textViewLog.getText() + (String)msg.obj + "\n");
	        }
	            break;

	        case MESSAGE_UI_TOAST:
	        {
	        	Toast.makeText(getApplicationContext(), (String) msg.obj, Toast.LENGTH_LONG).show();
	        }
	        	break;
   	        }
	    }
	};
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		getCurrentIPAddress();

		TextView textViewServer = (TextView) findViewById(R.id.textViewServer);
		textViewServer.setText(m_sCurrentIPAddress+":"+m_iServerPort);
		
		TextView textViewLog = (TextView) findViewById(R.id.textViewLog);
		textViewLog.setMovementMethod(new ScrollingMovementMethod());

		if(Helper_Camera.checkCameraHardware(getApplicationContext()))
		{
			/** create camera */
			if(!mCamera.open(Helper_Camera.getCamera()))
			{
				Toast.makeText(getApplicationContext(), "Cannot start camera !", Toast.LENGTH_LONG).show();
				return;
			}
			
			mPreview = new CameraPreview(this, mCamera);
			
			((FrameLayout) findViewById(R.id.layoutPreview)).addView(mPreview);
			
			mBroadcast = new CameraBroadcast(this, mCamera);
			
			mBroadcast.setOnEventListener(new CameraBroadcast.onEventListener()
			{

				@Override
				public void onConnected(String inetclient) {
					addLog("Get a connection from " + inetclient);
				}

				@Override
				public void onDisconnected(String inetclient) {
					addLog("Close connection from " + inetclient);
				}

				@Override
				public void onError(String sMessage) {
					addLog("Server error : "+sMessage);
				}
				
			});

			// Launch IP server
	        if(!mBroadcast.isConnected())
	        {
	        	Log.d(LOG_TAG, "Launch ip server on "+m_sCurrentIPAddress+":"+m_iServerPort+"...");
	        	addLog("Launch ip server on "+m_sCurrentIPAddress+":"+m_iServerPort+"...");
	        	if(!mBroadcast.createServer(m_iServerPort))
	        	{
	        		Log.d(LOG_TAG, "Error then start server :(");
	        		Toast.makeText(this, "Error then start server :(", Toast.LENGTH_LONG).show();
	        		addLog("Error then start server :(");
	        	}
	        }
		}
		else
		{
			Toast.makeText(getApplicationContext(), "Sorry, your device have no default camera !", Toast.LENGTH_LONG).show();
			addLog("Sorry, your device have no default camera !");
		}
	}
    @Override
    protected void onResume() {
        super.onResume();
        if(mCamera != null)
        	mCamera.startPreview();
    }

	@Override
    protected void onPause() {
        super.onPause();
        if(mCamera != null)
        	mCamera.stopPreview();
    }
	
	public void addLog(String sMsg)
	{
		_UI_Handler.sendMessage(_UI_Handler.obtainMessage(MESSAGE_UI_LOG, sMsg));
	}
	public void showToast(String sMsg)
	{
		_UI_Handler.sendMessage(_UI_Handler.obtainMessage(MESSAGE_UI_TOAST, sMsg));
	}
	
	private void getCurrentIPAddress() {
		m_sCurrentIPAddress = Helper_WiFi.getCurrentIPAddress_WiFi_Only(this, true);
		if(m_sCurrentIPAddress == "")
		{
			new AlertDialog.Builder(this)
			.setTitle("Not WiFi active connexion detected...")
			.setPositiveButton("Ok",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,
								int whichButton) {
							finish();
						}
					}).show();
			return;
		}
	}
}
